<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="mysql," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="此文为极客时间：MySQL实战45讲的 21、30、40节锁相关部分的总结  间隙锁的加锁原则 间隙锁加锁的情况，包含了两个“原则”、两个“优化”和一个“bug”。  原则 1：加锁的基本单位是 next-key lock。即间隙锁+行锁（前开后闭区间）。 原则 2：查找过程中访问到的对象才会加锁。 优化 1：索引上的等值查询，给唯一索引加锁的时候，next-key lock 退">
<meta property="og:type" content="article">
<meta property="og:title" content="《MySQL45讲》读书笔记(八)：间隙锁的加锁条件">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/11/09/mysql/%E3%80%8AMySQL45%E8%AE%B2%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0%EF%BC%88%E5%85%AB%EF%BC%89%EF%BC%9A%E9%97%B4%E9%9A%99%E9%94%81%E7%9A%84%E5%8A%A0%E9%94%81%E6%9D%A1%E4%BB%B6/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="此文为极客时间：MySQL实战45讲的 21、30、40节锁相关部分的总结  间隙锁的加锁原则 间隙锁加锁的情况，包含了两个“原则”、两个“优化”和一个“bug”。  原则 1：加锁的基本单位是 next-key lock。即间隙锁+行锁（前开后闭区间）。 原则 2：查找过程中访问到的对象才会加锁。 优化 1：索引上的等值查询，给唯一索引加锁的时候，next-key lock 退">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108173043844.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108173614816.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108173725306.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108175305570.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108180453457.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108181439263.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108182444617.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108182706835.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108183431275.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108183726684.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201108184255128.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201109202937260.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201109204020361.png">
<meta property="article:published_time" content="2020-11-08T16:00:00.000Z">
<meta property="article:modified_time" content="2020-12-24T12:01:06.247Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="mysql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20201108173043844.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/11/09/mysql/《MySQL45讲》读书笔记（八）：间隙锁的加锁条件/"/>





  <title>《MySQL45讲》读书笔记(八)：间隙锁的加锁条件 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/11/09/mysql/%E3%80%8AMySQL45%E8%AE%B2%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0%EF%BC%88%E5%85%AB%EF%BC%89%EF%BC%9A%E9%97%B4%E9%9A%99%E9%94%81%E7%9A%84%E5%8A%A0%E9%94%81%E6%9D%A1%E4%BB%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《MySQL45讲》读书笔记(八)：间隙锁的加锁条件</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-09T00:00:00+08:00">
                2020-11-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/mysql/" itemprop="url" rel="index">
                    <span itemprop="name">mysql</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.7k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>此文为极客时间：MySQL实战45讲的 21、30、40节锁相关部分的总结</p>
</blockquote>
<h2 id="间隙锁的加锁原则">间隙锁的加锁原则</h2>
<p>间隙锁加锁的情况，<strong>包含了两个“原则”、两个“优化”和一个“bug”。</strong></p>
<ol type="1">
<li>原则 1：加锁的基本单位是 next-key lock。即间隙锁+行锁（前开后闭区间）。</li>
<li>原则 2：查找过程中访问到的对象才会加锁。</li>
<li>优化 1：索引上的等值查询，给<strong>唯一索引加锁</strong>的时候，next-key lock 退化为行锁。</li>
<li>优化 2：索引上的等值查询，向右遍历时且最后一个值不满足等值条件的时候，next-key lock 退化为间隙锁。</li>
<li>一个 bug：唯一索引上的范围查询会访问到不满足条件的第一个值为止。</li>
</ol>
<p>以下面的表为例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`t`</span> (</span><br><span class="line">    <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span>,</span><br><span class="line">    <span class="string">`c`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">    <span class="string">`d`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">    PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>),</span><br><span class="line">    <span class="keyword">KEY</span> <span class="string">`c`</span> (<span class="string">`c`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> t <span class="keyword">values</span>(<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>),(<span class="number">5</span>,<span class="number">5</span>,<span class="number">5</span>),</span><br><span class="line">(<span class="number">10</span>,<span class="number">10</span>,<span class="number">10</span>),(<span class="number">15</span>,<span class="number">15</span>,<span class="number">15</span>),(<span class="number">20</span>,<span class="number">20</span>,<span class="number">20</span>),(<span class="number">25</span>,<span class="number">25</span>,<span class="number">25</span>);</span><br></pre></td></tr></table></figure>
<p>我们需要注意一下，c 是加了索引的，而 d 没有。直观点就是下图：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108173043844.png" alt="image-20201108173043844"><figcaption aria-hidden="true">image-20201108173043844</figcaption>
</figure>
<h2 id="一唯一索引等值查询间隙锁">一.唯一索引等值查询间隙锁</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201108173614816.png" alt="等值查询的间隙锁"><figcaption aria-hidden="true">等值查询的间隙锁</figcaption>
</figure>
<p>由于表 t 中没有 id=7 的记录，所以用我们上面提到的加锁规则判断一下的话：</p>
<ol type="1">
<li>根据原则 1，加锁单位是 next-key lock，session A 加锁范围就是 (5,10]；</li>
<li>同时根据优化 2，这是一个等值查询 (id=7)，而 id=10 不满足查询条件，next-key lock 退化成间隙锁，因此最终加锁的范围是 (5,10)。</li>
</ol>
<p>所以，session B 要往这个间隙里面插入 id=8 的记录会被锁住，但是 session C 修改 id=10 这行是可以的。</p>
<h2 id="二非唯一索引等值查询间隙锁">二.非唯一索引等值查询间隙锁</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201108173725306.png" alt="只加在非唯一索引下的锁"><figcaption aria-hidden="true">只加在非唯一索引下的锁</figcaption>
</figure>
<p>我们分析一下这个过程：</p>
<ol type="1">
<li>首先，根据原则1，会为（0,5] 范围加上 next-key lock；</li>
<li>由于 c 是普通索引，所以因此查到5以后不会停下，会向右遍历到第一个不符合条件的值，也就是10以后才会停下。所以锁的范围会扩张到（0,10]；</li>
<li>由于符合优化2，所以 next-key lock 会退化为间隙锁，也就是会变成（0,10）；</li>
<li>根据原则2，只有访问到的才加锁，也就是锁只加在c字段上，对主键索引是没关系的，所以 sessionB 可以更新成功。但 session C 要插入一个 (7,7,7) 的记录，就会被 session A 的间隙锁 (5,10) 锁住。</li>
</ol>
<p>需要注意，在这个例子中，<strong>lock in share mode 只锁覆盖索引</strong>，但是如果是 for update 就不一样了。 <strong>执行 for update 时，系统会认为你接下来要更新数据，因此会顺便给主键索引上满足条件的行加上行锁</strong>。</p>
<p>这个例子说明，锁是加在索引上的；同时，它给我们的指导是，如果你要用 lock in share mode 来给行加读锁避免数据被更新的话，就<strong>必须得绕过覆盖索引的优化，在查询字段中加入索引中不存在的字段</strong>。比如，将 session A 的查询语句改成 <code>select d from t where c=5 lock in share mode</code>。</p>
<h2 id="三唯一索引范围锁">三.唯一索引范围锁</h2>
<p>假如现在有两条 sql：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> t <span class="keyword">where</span> <span class="keyword">id</span>=<span class="number">10</span> <span class="keyword">for</span> <span class="keyword">update</span>;</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> t <span class="keyword">where</span> <span class="keyword">id</span>&gt;=<span class="number">10</span> <span class="keyword">and</span> <span class="keyword">id</span>&lt;<span class="number">11</span> <span class="keyword">for</span> <span class="keyword">update</span>;</span><br></pre></td></tr></table></figure>
<p>在逻辑上，两条 sql 是等价的，但是加锁的情况是不一样的。以第二条 sql 为例：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108175305570.png" alt="主键索引范围锁"><figcaption aria-hidden="true">主键索引范围锁</figcaption>
</figure>
<ol type="1">
<li>首先加了一个范围为 （5,10] 的 next-key lock，由于id 是唯一索引，根据优化1锁会退化为行锁，也就是只锁id=10；</li>
<li>由于是范围查找，会继续向右遍历，找到id=15的行发现第一条不符合 id&lt;10 的数据，然后加上（10，15]的锁。</li>
</ol>
<p>也就是说，最终 sessionA 会加上 [10,15] 的锁。</p>
<p>需要注意一点，首次 session A 定位查找 id=10 的行的时候，是当做等值查询来判断的，而向右扫描到 id=15 的时候，用的是范围查询判断。也就是说，&gt;= 这个查询，<strong>实际上是等值+范围查询，两次锁的分别加上的</strong>。</p>
<h2 id="四非唯一索引范围锁">四.非唯一索引范围锁</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201108180453457.png" alt="非唯一索引范围锁"><figcaption aria-hidden="true">非唯一索引范围锁</figcaption>
</figure>
<ul>
<li>首先，由于 c&gt;=10 满足的第一条数据就是 c=10 的这行，因此会加上（5,10] 的 next-key lock，由于 c 不是唯一索引，所以不符合优化1的条件，所以最终加锁范围还是（5,10]</li>
<li>由于是范围查找，继续向右遍历，直到找到第一行不符合 c&lt;11 的数据，也就是 c=15 这行，加上（10，15] 的，由于后半段是范围查询，所以不符合优化2的条件，所以最终加锁范围还是（10,15]</li>
</ul>
<p>也就是说，最终 sessionA 会加上 （5,15] 的锁。</p>
<h2 id="五唯一索引范围锁-bug">五.唯一索引范围锁 bug</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201108181439263.png" alt="唯一索引范围锁 bug"><figcaption aria-hidden="true">唯一索引范围锁 bug</figcaption>
</figure>
<p>session A 是一个范围查询，按照原则 1 的话，应该是索引 id 加上 (10,15] 这个 next-key lock。并且因为 id 是唯一键，相比于情况三，id = 15的这条数据是存在的，所以循环判断到 id=15 这一行就应该停止了。</p>
<p>但是实现上，InnoDB 会往前扫描到第一个不满足条件的行为止，也就是 id=20。而且由于这是个范围扫描，因此索引 id 上的 (15,20] 这个 next-key lock 也会被锁上。</p>
<h2 id="六两个相同的非唯一索引上的等值查询">六.两个相同的非唯一索引上的等值查询</h2>
<h3 id="1不加limit的情况">1.不加limit的情况</h3>
<p>现在已经有了（10,10,10）这条数据，再插入（30,10,30），也就是说，现在有两条 c = 10 的数据。但是由于非唯一索引上包含主键的值，所以两种是不可能完全相同的，这两条数据也有间隙。</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108182444617.png" alt="两个相同的非唯一索引上的间隙"><figcaption aria-hidden="true">两个相同的非唯一索引上的间隙</figcaption>
</figure>
<p>在上图的状态，执行sql：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108182706835.png" alt="delete 示例"><figcaption aria-hidden="true">delete 示例</figcaption>
</figure>
<ol type="1">
<li>先找到第一条 c=10 的数据，也就是 id=10 的这行，加上（5,10] 的锁;</li>
<li>向右遍历，一直到第一个不符合条件的数据，也就是加上（10,15] 的锁。注意，这里指的是id，也就是现在这个区间的锁包含了id为（30,15,20）这三条数据和他们的间隙。由于这是等值查询，根据优化1，会退化为间隙锁，也就是变成（10,15）；</li>
</ol>
<p>也就是说，现在加锁的就会变成：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108183431275.png" alt="相同索引的等值查询加锁范围"><figcaption aria-hidden="true">相同索引的等值查询加锁范围</figcaption>
</figure>
<h3 id="2加limit限制的情况">2.加limit限制的情况</h3>
<p>现在，在上文的 delete 的情况加上 limit：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201108183726684.png" alt="加了limit语句限制的情况"><figcaption aria-hidden="true">加了limit语句限制的情况</figcaption>
</figure>
<p>加锁的逻辑会有一点变化：</p>
<ol type="1">
<li>依然先加（5,10] 的锁；</li>
<li>向右遍历找到第二条符合条件的数据，即 id=30 的数据。由于加上了 limit ，已经找到两条了，所以就不必向后再找到一条不符合的数据了，也就不需要加上（30,15）的锁了。</li>
</ol>
<figure>
<img src="http://img.xiajibagao.top/image-20201108184255128.png" alt="加了limit语句限制的锁范围"><figcaption aria-hidden="true">加了limit语句限制的锁范围</figcaption>
</figure>
<p>可以看见，这样做减少了锁的范围。</p>
<p>这个例子对我们实践的指导意义就是，<strong>在删除数据的时候尽量加 limit</strong>。这样不仅可以控制删除数据的条数，让操作更安全，还可以减小加锁的范围。</p>
<h2 id="七-间隙锁的扩大">七、间隙锁的扩大</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201109202937260.png" alt="间隙锁的扩大"><figcaption aria-hidden="true">间隙锁的扩大</figcaption>
</figure>
<p>我们来分析一下：</p>
<ol type="1">
<li>由于 id &lt;= 15 第一条满足的数据就是 id=15 这条数据，因此加上 (10,15] 的锁，因为 id &gt; 10，所以不必再理id=10之前的数据了。由于是一个等值查询，所以（10,15] 退化为间隙锁（10,15）；</li>
<li>sessionB 删除了 id=10 这行数据，由于没锁到 id=10，所以顺利删除了该数据；</li>
<li>由于缺少了10，所以原本（10,15）的间隙锁扩大为（5,15），因此插入语句被阻塞。</li>
</ol>
<p>类似的例子还有这个：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201109204020361.png" alt="间隙锁的扩大2"><figcaption aria-hidden="true">间隙锁的扩大2</figcaption>
</figure>
<ol type="1">
<li>sessionA 加上了 ( 5,supremum] 的锁；</li>
<li>sessionB 将 c=5 变成了 c=1，现在锁扩大到了（1,supremum]；</li>
<li>sessionB 试图将 c=5 变成 c=1，此时c=5已经在锁的范围了，因此更新的sql被堵塞。</li>
</ol>
<h2 id="八-总结">八、总结</h2>
<p>分析间隙锁的加锁原则：两个原则，两个优化，一个bug。</p>
<p>加锁的对象一般来说是索引，也就是说，只要更新使用的索引跟上锁的索引不一样，就不会影响到插入间隙的行为。除非使用 for update，这会为整段数据都加上锁。</p>
<p>加锁单位是 next-key lock，即间隙锁+行锁，是一个前开后闭的区间。也就是，访问到了A，那么锁就是（A-1，A]，即实际上加锁范围由间隙右边的节点决定。</p>
<p>有且仅在等值查询的过程，对于唯一索引，锁有可能退化为行锁也可能退化为间隙锁；但是对于非唯一索引，锁只可能退化为间隙锁。</p>
<p>如果删除了间隙锁的“边界”，会导致间隙锁的扩大。</p>
<p>对于唯一索引：</p>
<ol type="1">
<li>等值查询：先加本段的 next-key lock，即前面一段间隙锁加本行行锁。如果本行即使要查询的数据，就退化为行锁，否则就退化为间隙锁。</li>
<li>范围查询：同上，但是必然会向后查找到第一个不符合的数据，先加上后半段的 next-key lock，再退化为间隙锁。</li>
</ol>
<p>对于非唯一索引：</p>
<ol type="1">
<li>等值查询：先加本段的 next-key lock，不管要查找的值存不存在，必在查找值的基础上向后找到第一条不符合的数据，加上 next-key lock，再让后半段锁退化为间隙锁。</li>
<li>范围查询：同上，由于不是等值查询所以不符合优化2的条件，相比等值查询，他的后半段还是 next-key lock 而不会退化为间隙锁。</li>
<li>多个重复的索引值，不加 limit：可以看成特殊的范围查询，会把第一个索引位置的前半段加上 next-key lock，然后再为第一到最后一个索引位置的这段区域全加上 next-key lock，最后再向后查找到第一个不符合条件的值，并加上 next-key lock，由于也算等值查询，根据优化2后半段从 next-key lock退化为间隙锁。</li>
<li>多个重复的索引值，加 limit：同上，但是由于加了条数限制，所以不必再向后查找到第一个不符合条件的值，所以相比不加 limit 少加最后一个索引位置的之后的一段间隙锁。</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/mysql/" rel="tag"># mysql</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/11/03/java/JDK%E6%96%B0%E7%89%B9%E6%80%A7/JDK1.8%E6%96%B0%E7%89%B9%E6%80%A7%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9AOptional%E7%B1%BB/" rel="next" title="JDK1.8新特性（四）：Optional类">
                <i class="fa fa-chevron-left"></i> JDK1.8新特性（四）：Optional类
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/11/11/mysql/%E3%80%8AMySQL45%E8%AE%B2%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0%EF%BC%88%E4%B9%9D%EF%BC%89%EF%BC%9A%E5%85%B3%E4%BA%8E%E5%85%83%E6%95%B0%E6%8D%AE%E9%94%81%20online%20ddl%E6%8F%92%E9%98%9F%E9%97%AE%E9%A2%98/" rel="prev" title="《MySQL45讲》读书笔记(九)：关于元数据锁 online ddl插队问题">
                《MySQL45讲》读书笔记(九)：关于元数据锁 online ddl插队问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%97%B4%E9%9A%99%E9%94%81%E7%9A%84%E5%8A%A0%E9%94%81%E5%8E%9F%E5%88%99"><span class="nav-text">间隙锁的加锁原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E7%AD%89%E5%80%BC%E6%9F%A5%E8%AF%A2%E9%97%B4%E9%9A%99%E9%94%81"><span class="nav-text">一.唯一索引等值查询间隙锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E9%9D%9E%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E7%AD%89%E5%80%BC%E6%9F%A5%E8%AF%A2%E9%97%B4%E9%9A%99%E9%94%81"><span class="nav-text">二.非唯一索引等值查询间隙锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E8%8C%83%E5%9B%B4%E9%94%81"><span class="nav-text">三.唯一索引范围锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B%E9%9D%9E%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E8%8C%83%E5%9B%B4%E9%94%81"><span class="nav-text">四.非唯一索引范围锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E8%8C%83%E5%9B%B4%E9%94%81-bug"><span class="nav-text">五.唯一索引范围锁 bug</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD%E4%B8%A4%E4%B8%AA%E7%9B%B8%E5%90%8C%E7%9A%84%E9%9D%9E%E5%94%AF%E4%B8%80%E7%B4%A2%E5%BC%95%E4%B8%8A%E7%9A%84%E7%AD%89%E5%80%BC%E6%9F%A5%E8%AF%A2"><span class="nav-text">六.两个相同的非唯一索引上的等值查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E4%B8%8D%E5%8A%A0limit%E7%9A%84%E6%83%85%E5%86%B5"><span class="nav-text">1.不加limit的情况</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%8A%A0limit%E9%99%90%E5%88%B6%E7%9A%84%E6%83%85%E5%86%B5"><span class="nav-text">2.加limit限制的情况</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83-%E9%97%B4%E9%9A%99%E9%94%81%E7%9A%84%E6%89%A9%E5%A4%A7"><span class="nav-text">七、间隙锁的扩大</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AB-%E6%80%BB%E7%BB%93"><span class="nav-text">八、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
